import React, { useEffect, useState } from 'react';
import { Table, Tag, Button, message, Modal, Form, DatePicker, Switch } from 'antd';
import { CrownOutlined } from '@ant-design/icons';
import api, { API_URLS } from '../../utils/api';
import dayjs from 'dayjs';

interface User {
  id: number;
  email: string;
  username: string;
  is_vip: boolean;
  vip_expire_date: string | null;
}

const VipManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingUser, setEditingUser] = useState<User | null>(null);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await api.get(API_URLS.VIP);
      setUsers(response.data);
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleEdit = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue({
      email: user.email,
      username: user.username,
      is_vip: user.is_vip,
      vip_expire_date: user.vip_expire_date ? dayjs(user.vip_expire_date) : null,
    });
    setModalVisible(true);
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingUser) {
        const submitData = {
          ...values,
          vip_expire_date: values.vip_expire_date?.format('YYYY-MM-DD'),
        };
        await api.put(`${API_URLS.USER_DETAIL(editingUser.id.toString())}/vip`, submitData);
        message.success('VIP状态更新成功');
      }
      setModalVisible(false);
      fetchUsers();
    } catch (error) {
      message.error('更新VIP状态失败');
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'VIP状态',
      dataIndex: 'is_vip',
      key: 'is_vip',
      render: (is_vip: boolean) => (
        <Tag color={is_vip ? 'gold' : 'default'} icon={<CrownOutlined />}>
          {is_vip ? 'VIP会员' : '普通用户'}
        </Tag>
      ),
    },
    {
      title: 'VIP到期时间',
      dataIndex: 'vip_expire_date',
      key: 'vip_expire_date',
      render: (date: string | null) => date ? dayjs(date).format('YYYY-MM-DD') : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Button type="link" onClick={() => handleEdit(record)}>
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div>
      <h2>VIP会员管理</h2>
      <Table
        columns={columns}
        dataSource={users}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title="编辑VIP状态"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
        >
          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ required: true, message: '请输入邮箱' }]}
          >
            <input disabled />
          </Form.Item>

          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <input disabled />
          </Form.Item>

          <Form.Item
            name="is_vip"
            label="VIP状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="VIP" unCheckedChildren="普通用户" />
          </Form.Item>

          <Form.Item
            name="vip_expire_date"
            label="VIP到期时间"
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default VipManagement; 